package com.aiyige.page.my.order.refund;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.JsonUtil;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.base.eventbus.EventOrderChanged;
import com.aiyige.model.OrderEntity;
import com.aiyige.model.moment.entity.Moment;
import com.aiyige.page.my.order.adapter.refund.RefundImageEntity;
import com.aiyige.page.my.order.adapter.refund.RefundPicListAdapter;
import com.aiyige.page.my.order.model.RefundReasonModel;
import com.aiyige.page.my.order.model.RequestRefund;
import com.aiyige.page.my.order.refund.model.RefundRespModel;
import com.aiyige.page.my.order.refund.util.RefundServiceModel;
import com.aiyige.setup.model.Setup;
import com.aiyige.setup.util.SetupUtil;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.InputNumFilter;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.SafeAsyncTask;
import com.aiyige.utils.StringUtils;
import com.aiyige.utils.TextWatcherAdapter;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.UploadPhotoUtil;
import com.aiyige.utils.dialog.LoadingDialog;
import com.aiyige.utils.widget.CommonTitleDetailDialog;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import org.greenrobot.eventbus.EventBus;

import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Response;
import timber.log.Timber;

/**
 * 退款申请页
 */
@Route(path = ARouterConfig.RefundApplyForPage, extras = ARouterConfig.EXTRA_NEED_LOGIN)
public class RefundApplyForPage extends RefundBaseActivity implements SelectRefundReasonDialog.Listener {
    public static final int MAX_REFUND_IMAGE_NUM = 9;
    private final static int REQUEST_CODE_SELECT_IMAGE = 120;
    public static final int MAX_REFUND_REASON_INPUT_NUM = 200;

    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;

    @BindView(R.id.rl_the_refund_reason)
    RelativeLayout refundReason;

    @BindView(R.id.tv_refund_reason)
    TextView tvRefundReason;

    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.tv_input_count)
    TextView tv_input_count;

    @BindView(R.id.btn_submit)
    Button btnSubmit;

    @BindView(R.id.tv_pay_money)
    TextView tvPayMoney; // 付款金额

    @BindView(R.id.tv_service_charge)
    TextView tvServiceCharge; // 手续费

    @BindView(R.id.tv_but_the_refund_amount)
    TextView tvButTheRefundAmount; // 可退金额

    @BindView(R.id.tv_service_charge_tag)
    TextView tvServiceChargeTag; // 卖家承担手续费


    @Autowired
    OrderEntity orderEntity = null;

    RefundPicListAdapter refundPicListAdapter;
    RefundReasonModel selectedRefundReasonModel = new RefundReasonModel();
    List<RefundReasonModel> refundReasonModelList = new LinkedList<>();
    String refundDescription = "";
    InputNumFilter inputNumFilter;

    RefundServiceModel refundServiceModel = new RefundServiceModel();

    @Override
    protected int getLayoutResourceId() {
        return R.layout.refund_apply_page;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        ARouter.getInstance().inject(this);
        super.onCreate(savedInstanceState);
        init();
    }

    @Override
    protected OrderEntity getOrderEntity() {
        return orderEntity;
    }

    private void init() {
        initTitleLayout(getString(R.string.apply_refund));
        btnSubmit.setVisibility(View.VISIBLE);
        inputNumFilter = new InputNumFilter(MAX_REFUND_REASON_INPUT_NUM);
        inputNumFilter.setListener(new InputNumFilter.Listener() {
            @Override
            public void inputNum(int num) {
                tv_input_count.setText(StringUtils.getString(R.string.input_num_count, num, MAX_REFUND_REASON_INPUT_NUM));
            }
        });
        etContent.setFilters(new InputFilter[]{inputNumFilter});
        etContent.addTextChangedListener(new TextWatcherAdapter() {
            @Override
            public void afterTextChanged(Editable s) {
                refundDescription = s.toString();
            }
        });
        refundPicListAdapter = new RefundPicListAdapter();
        recyclerview.setLayoutManager(new GridLayoutManager(this, 4));
        refundPicListAdapter.bindToRecyclerView(recyclerview);
        refundPicListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                try {
                    RefundImageEntity refundImageEntity = (RefundImageEntity) adapter.getItem(position);
                    switch (refundImageEntity.getType()) {
                        case RefundImageEntity.TYPE_ADD:
                            openPictureSelector();
                            break;
                        case RefundImageEntity.TYPE_NORMAL:
                            adapter.remove(position);
                            if (((RefundImageEntity) adapter.getItem(adapter.getData().size() - 1)).getType() != RefundImageEntity.TYPE_ADD) {
                                adapter.addData(RefundImageEntity.newBuilder()
                                        .type(RefundImageEntity.TYPE_ADD)
                                        .build());
                            }
                            break;
                    }
                } catch (Exception e) {
                }
            }
        });
        refundReason.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SelectRefundReasonDialog dialog = new SelectRefundReasonDialog();
                dialog.setSelected(selectedRefundReasonModel);
                dialog.setData(refundReasonModelList);
                dialog.show(getSupportFragmentManager(), null);
                dialog.setLisenter(RefundApplyForPage.this);
            }
        });
        refundPicListAdapter.addData(RefundImageEntity.newBuilder()
                .type(RefundImageEntity.TYPE_ADD)
                .build());
        new RequestRefundReasonTask(this).execute();


        if (orderEntity != null) {
            tvPayMoney.setText("￥" + StringUtils.priceFormat(orderEntity.getPayAmount()));
            tvServiceCharge.setText("-￥" + StringUtils.priceFormat(orderEntity.getUserFee()));
            tvButTheRefundAmount.setText("￥" + StringUtils.priceFormat(orderEntity.getPayAmount() - orderEntity.getUserFee()));

        }
    }

    public boolean checkFormValidity() {
        if (selectedRefundReasonModel == null || TextUtils.isEmpty(selectedRefundReasonModel.getId())) {
            ToastX.show(StringUtils.getString(R.string.please_select_refund_reason));
            return false;
        }
        return true;
    }

    public class RequestRefundReasonTask extends SafeAsyncTask<Object, Object, Object> {

        public RequestRefundReasonTask(Activity activity) {
            super(activity, R.string.loading);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            refundReason.setEnabled(false);
        }

        @Override
        public void safeOnPostExecute(Object o) {
            if (o instanceof Exception) {
                ToastX.show((Exception) o);
            } else {
                refundReason.setEnabled(true);
            }
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                String subGroupType = SetupUtil.SUB_GROUP_TYPE_MAJOR_COURSE;
                try {
                    switch (orderEntity.getGoodsType()) {
                        case Moment.SUBJECT_MAJOR_COURSE:
                            subGroupType = SetupUtil.SUB_GROUP_TYPE_MAJOR_COURSE;
                            break;
                    }
                } catch (Exception e) {
                }
                Response<ResponseBody> response = ApiManager.getService().findSetupByGroupTypeAndSubGroupType(SetupUtil.GROUP_TYPE_APPLY_REFUND_REASON, subGroupType).execute();
                if (response.code() != ResponseCode.OK) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                String json = RetrofitUtil.getResponseBodyAsString(response);
                List<Setup> setupList = JSON.parseArray(json, Setup.class);
                for (Setup setup : setupList) {
                    refundReasonModelList.add(RefundReasonModel.newBuilder()
                            .id(setup.getId())
                            .title((String) setup.getData().get("name"))
                            .personLiable((String) setup.getData().get("personLiable"))
                            .userFeeSummary((String) setup.getData().get("userFeeSummary"))
                            .userFeeDetail((String) setup.getData().get("userFeeDetail"))
                            .refundFeeDetail((String) setup.getData().get("refundFeeDetail"))
                            .build());
                }
                return null;
            } catch (Exception e) {
                return e;
            }
        }
    }

    @OnClick({R.id.btn_submit})
    public void onViewClick(View v) {
        switch (v.getId()) {
            case R.id.btn_submit:
                if (checkFormValidity()) {
                    new RequestRefundTask(this).execute();
                }
                break;
            case R.id.tv_service_charge_tag:
                if (selectedRefundReasonModel == null) {
                    return;
                }
                CommonTitleDetailDialog.newInstance(getString(R.string.refund_notice),selectedRefundReasonModel.isBuyerPay()?selectedRefundReasonModel.getUserFeeDetail():selectedRefundReasonModel.getRefundFeeDetail(),null,getResources().getString(R.string.know_the))
                        .show(getSupportFragmentManager(),null);
                break;
        }
    }

    @Override
    protected void onActivityResult(final int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_SELECT_IMAGE) {
            List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
            if (!ListUtil.isEmpty(selectList)) {
                LocalMedia localMedia = selectList.get(0);
                UploadPhotoUtil.newBuilder()
                        .listener(new UploadPhotoUtil.Listener() {
                            LoadingDialog loadingDialog;

                            @Override
                            public void onPreUpload() {
                                loadingDialog = LoadingDialog.newBuilder()
                                        .with(RefundApplyForPage.this)
                                        .message(R.string.uploading)
                                        .show();
                            }

                            @Override
                            public void onProgress(double progress) {
                                Timber.e("onProgress:" + progress);
                            }

                            @Override
                            public void onFail(Throwable t) {
                                loadingDialog.dismiss();
                                ToastX.show(t.getMessage());
                            }

                            @Override
                            public void onFinish(String url) {
                                loadingDialog.dismiss();
                                RefundImageEntity info = RefundImageEntity.newBuilder()
                                        .type(RefundImageEntity.TYPE_NORMAL)
                                        .path(url)
                                        .build();
                                refundPicListAdapter.addData(refundPicListAdapter.getData().size() - 1, info);
                                if (refundPicListAdapter.getData().size() > MAX_REFUND_IMAGE_NUM) {
                                    refundPicListAdapter.remove(refundPicListAdapter.getData().size() - 1);
                                }
                            }
                        }).photoLocalUrl(localMedia.getPath())
                        .build()
                        .upload();
            }
        }
    }


    public void openPictureSelector() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .selectionMode(PictureConfig.SINGLE)
                .previewImage(false)
                .isCamera(true)
                .compress(false)
                .enableCrop(false)
                .isZoomAnim(false)
                .previewEggs(false)
                .forResult(REQUEST_CODE_SELECT_IMAGE);
    }

    @Override
    public void onSelect(RefundReasonModel value) {
        selectedRefundReasonModel = value;
        tvRefundReason.setText(value.getTitle());
        tvRefundReason.setTextColor(ContextCompat.getColor(this, R.color.zwcolor_black_111111));
        if (orderEntity.hasServiceCharge()) {
            tvServiceChargeTag.setVisibility(View.VISIBLE);
            tvServiceChargeTag.setText(value.getUserFeeSummary());
        }
    }


    public class RequestRefundTask extends SafeAsyncTask<Object, Object, Object> {
        OrderEntity respOrderEntity = null;

        public RequestRefundTask(Activity activity) {
            super(activity, R.string.text_process);
        }

        @Override
        public void safeOnPostExecute(Object o) {
            if (o instanceof Exception) {
                ToastX.show((Exception) o);
            } else {
                EventBus.getDefault().post(EventOrderChanged.newBuilder()
                        .orderEntity(respOrderEntity)
                        .build());
                finish();
            }
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                List<String> imageUrlList = new LinkedList<>();
                for (RefundImageEntity entity : refundPicListAdapter.getData()) {
                    if (entity.getType() != RefundImageEntity.TYPE_NORMAL) continue;
                    imageUrlList.add(entity.getPath());
                }
                RequestRefund requestRefund = RequestRefund.newBuilder()
                        .refundDescription(refundDescription)
                        .refundReason(selectedRefundReasonModel.getTitle())
                        .refundReasonId(selectedRefundReasonModel.getId())
                        .orderId(orderEntity.getOrderId())
                        .imageUrls(imageUrlList)
                        .build();
                Response<ResponseBody> response = ApiManager.getService().requestRefund(requestRefund).execute();
                if (response.code() != ResponseCode.CREATED) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                String json = RetrofitUtil.getResponseBodyAsString(response);
                RefundRespModel refundRespModel = JsonUtil.toObject(json, RefundRespModel.class);
                if (refundRespModel == null) {
                    throw new Exception("Order为空");
                }
                respOrderEntity = new OrderEntity(refundRespModel.getOrderBackup());
                return null;
            } catch (Exception e) {
                return e;
            }
        }
    }

}
